package 网络编程.TCPECHO;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 石方旭
 * Date: 2022-10-04
 * Time: 22:24
 */
public class TCPEchoClint1 {

    Socket socket = null;
    public TCPEchoClint1() throws IOException {
        socket = new Socket("127.0.0.1", 8000);
    }
    public void start() throws IOException {
        System.out.println("客户端启动");
        Scanner scan = new Scanner(System.in);
        byte[] bytes = new byte[127];
        int readlen = 0;
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
           while (true){
               System.out.print(">");
               //从控制台上读取请求
               String request = scan.next();
               //写入给客户端
               outputStream.write(request.getBytes());
               socket.shutdownOutput();
               String response = "";
               //读取服务器返回的响应
               while((readlen = inputStream.read(bytes))!=-1){
                   response = new String(bytes,0,readlen);
               }
               System.out.printf("req = %s;rep = %s\n",request,response);
           }
        }finally {
            socket.close();
        }
    }

    public static void main(String[] args) throws IOException {
        TCPEchoClint1 tcpEchoClint1 = new TCPEchoClint1();
        tcpEchoClint1.start();
    }

}
